package http.secure.common.filter;

import http.secure.common.constant.SecureConstant;
import http.secure.common.keys.KeySwitcher;
import http.secure.common.keys.SecureKeyStore;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequiredArgsConstructor
public class ExchangeHandler {
    private final KeySwitcher keySwitcher;
    private final SecureKeyStore keyStore;

    /**
     * 密钥交换内部方法
     */
    public String exchange(@RequestBody String body,
                           @RequestHeader("x-server-digest") String serverSign,
                           @RequestHeader("x-client-digest") String clientSign,
                           @RequestHeader("x-browser-sign") String browserSign,
                           HttpServletResponse response) {
        try {
            if (StrUtil.isAllNotEmpty(serverSign, clientSign)) {
                return keySwitcher.exchange(body, serverSign, clientSign, browserSign);
            }
        } catch (Exception e) {
            log.warn("exchange error: {}", e.getMessage());
        }
        response.setStatus(404);
        return null;
    }

    /**
     * 密钥轮换方法
     */
    public String rotation() {
        String cpk = keyStore.get(SecureConstant.CLIENT_PUB_KEY);
        return keySwitcher.rotationKeys(cpk);
    }
}
